package apis

import (
	"strings"
	"time"

	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/ws"
	"github.com/mitchellh/mapstructure"

	"ssdevice/common/constant"
	"ssdevice/common/utils"
	"ssdevice/internal/device/models"
	"ssdevice/internal/device/models/query"
)

// 首次连接查询数据
func connGetData(c *ws.Client) [][]byte {
	if c == nil {
		return nil
	}
	req := query.SysDevSensorQuery{}
	_ = mapstructure.Decode(c.Auth, &req.UserInfo)
	req.Sns = c.Param.Sn
	req.Keys = c.Param.Key
	if len(c.Param.ProductModel) > 0 {
		req.ProductModelIn = strings.Split(strings.ReplaceAll(c.Param.ProductModel, " ", ""), ",")
	}
	sensorM := models.SysDevSensor{}
	sensorM.Orm = env.Db
	err, result := sensorM.FindSensorList(&req)
	if err != nil || result == nil {
		return nil
	}
	arr := make([][]byte, 0)
	aggData := make(map[string]map[string]interface{})
	// 按sn-time聚合sensor
	if _, ok := result.([]models.SysDevSensor); ok {
		for _, sensor := range result.([]models.SysDevSensor) {
			sn := sensor.Sn
			updateTime := sensor.UpdateTime
			if updateTime == nil {
				continue
			}
			t := time.Time(*updateTime).Format("2006-01-02 15:04:05")
			k := sn + "#" + t
			if _, ok := aggData[k]; !ok {
				aggData[k] = make(map[string]interface{})
			}
			m := utils.BytesToMap(sensor.Data)
			aggData[k][sensor.Key] = m[sensor.Key]
		}
	}
	// 每sn发一条
	for key, data := range aggData {
		sn := strings.Split(key, "#")[0]
		updateTime := strings.Split(key, "#")[1]
		arr = append(arr, utils.MapToBytes(map[string]interface{}{
			"msgType":    "sensor",
			"sn":         sn,
			"data":       data,
			"updateTime": updateTime,
		}))
	}
	return arr
}

const localKeyDept = "sndeptid#"
const localKeyModel = "snpmodel#"

// 减轻redis压力
const localKeyTimeout = 5 * time.Minute

// 推送消息权限过滤(设备)
func clientMsgFilter(c *ws.Client, item string) bool {
	if c == nil {
		return false
	}
	sn := strings.Split(item, "#")[1]
	// client有请求Sn参数，但不包含该设备
	if len(c.Param.Sn) > 0 && !utils.StrIn(sn, strings.Split(strings.ReplaceAll(c.Param.Sn, " ", ""), ",")) {
		return false
	}
	var deptId string
	depti, ok := constant.LocalCache.Get(localKeyDept + sn)
	if !ok || depti == nil {
		deptId, _ = env.Cache.HashGet(constant.DeviceDeptCache, sn)
		constant.LocalCache.Set(localKeyDept+sn, deptId, localKeyTimeout)
	} else {
		deptId = depti.(string)
	}
	if len(deptId) == 0 {
		return false
	}
	// client无此设备sn的权限
	if !utils.StrIn(deptId, c.Auth.DeptIdList) {
		return false
	}
	// client有请求deptId参数，但不包含该设备分组
	if len(c.Param.DeptId) > 0 && !utils.StrIn(deptId, strings.Split(strings.ReplaceAll(c.Param.DeptId, " ", ""), ",")) {
		return false
	}
	// client有请求productModel参数，但不包含该设备所属产品
	if len(c.Param.ProductModel) > 0 {
		var pmodel string
		pmodeli, ok := constant.LocalCache.Get(localKeyModel + sn)
		if !ok || pmodeli == nil {
			devCache, _ := env.Cache.HashGet(constant.DeviceEasyCache, sn)
			if len(devCache) == 0 {
				return false
			}
			info := utils.BytesToMap([]byte(devCache))
			pmodel = utils.If(info["productModel"] != nil, info["productModel"], "").(string)
			constant.LocalCache.Set(localKeyModel+sn, pmodel, localKeyTimeout)
		} else {
			pmodel = pmodeli.(string)
		}
		if len(pmodel) == 0 {
			return false
		}
		if !utils.StrIn(pmodel, strings.Split(strings.ReplaceAll(c.Param.ProductModel, " ", ""), ",")) {
			return false
		}
	}
	return true
}

// 接收client消息处理
func clientMsgIn(c *ws.Client, message []byte) {
	//if c == nil {
	//	return
	//}
	//c.SendMessage([]byte("已收到你发的:" + string(message)))
}
